<?php
namespace jy_guashop;
defined('BY_JYA') or exit('error');
/*
	社区分润计算	
*/
class commission extends \plugin{
	public function create($order){
		$this->teamsetting=$this->plugin_setting('teamsetting');
		if(!$this->teamsetting['isopen']){
			return false;
		}
		$this->order=$order;
		$member=$this->get('member',array('mid'=>$order['mid']),array('mid','is_agent','fromuser','level_id'));
		$this->lastlevel=$member['level_id'];
		$maxlevel=$this->get('teamlevel',array('uniacid'=>$_SESSION['uniacid']),'','','level desc');
		$maxlevel=$maxlevel['level'];
		$this->commission_order['maxlevel']=$maxlevel;
		$fromuser=$member['fromuser'];
		//自购升级
		if($member['is_agent']){
			$this->model('member')->update_agent_level($order['mid'],$order['id']);
		}
		if($this->order['price']<=0 || !$fromuser){
			return;
		}
		if($this->order['buy_credit3'][1]>0){
			$this->order['buy_credit'] +=$this->order['buy_credit3'][1];
		}
		$this->commission_order=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$this->order['mid'],
				'ordersn'=>$this->order['ordersn'],
				'order_price'=>$this->order['price'],
				'buy_credit'=>$this->order['buy_credit'],
				'commission_money'=>0,
				'jinfen1'=>0,
				'jinfen6'=>0,
				'ji_money'=>0,
				'area_money'=>0,
				'createtime'=>TIMESTAMP,
		);
		//佣金计算方式，是否扣除运费
		if($this->teamsetting['commissionfeetype']==1){
			$this->commission_order['commission_price']=$this->order['price'];
		}elseif($this->teamsetting['commissionfeetype']==3){
			$this->commission_order['commission_price']=$this->order['price'] + $this->order['deductcredit'] + $this->order['deductcredit2'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		//当分销层级大于0时，逐次寻找上级推荐人并计算佣金
		$levelnum=12;
		for($i=0;$i<$levelnum;$i++){
			if(!$fromuser){
				break;
			}
			$member=$this->get('member',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']));
			$fromuser=$member['fromuser'];
			$this->create_commission($member,$i+1);
			//如果他的上级是我
			$this->lastlevel=$member['level_id'];
			$ta_fromuser=$this->getcolumn('member',array('mid'=>$member['fromuser']),'fromuser');
			if(($fromuser>0 && $ta_fromuser==$fromuser) || $fromuser==$member['mid']){
				break;
			}
		}
		//生成分销订单
		$indata=$this->commission_order;
		unset($indata['ji_money']);
		unset($indata['maxlevel']);
		unset($indata['isarea']);
		$this->insert('fee_order',$indata);
		if($order['sendtype']==3){
			$status=pdo_getcolumn('jy_weishop_order',array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']),'status');
			if($status==3){
				$this->order_complete($order);
			}
		}
		return true;
	}
	//计算收益
	public function create_commission($member=array(),$commission_level=1){
		if(!$member['level_id']){
			return false;
		}
		$level=pdo_get('jy_guashop_teamlevel',array('uniacid'=>$_SESSION['uniacid'],'id'=>$member['level_id']));
		$fee_per1=$level['fee_per1'];
		$fee_per2=$level['fee_per2'];
		$jifen_per1=$level['jifen_per1'];
		$jifen_per2=$level['jifen_per2'];
		$ping_per=$level['ping_per'];
		$money_fee_per1=0;
		$money_fee_per2=0;
		$money_jifen_per1=0;
		$money_jifen_per2=0;
		$order_price=$this->commission_order['commission_price'];
		$buy_credit=$this->commission_order['buy_credit'];
		$remark=array(
				'level_id'=>$commission_level,
				'commission_level'=>$commission_level,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
		);
		//购物送积分
		if($buy_credit>0){
			if(substr($fee_per1,-1)=='%'){
				$money_fee_per1 +=($buy_credit*substr($fee_per1,0,-1))/100;
			}else{
				$money_fee_per1 +=$fee_per1;
			}
			if(substr($fee_per2,-1)=='%'){
				$money_fee_per2 +=($buy_credit*substr($fee_per2,0,-1))/100;
			}else{
				$money_fee_per2 +=$fee_per2;
			}
		}
		//直推能量值收益
		if($money_fee_per1>0 && $commission_level==1){
			$this->commission_order['jinfen6']+=$money_fee_per1;
			$new_commission=array(
				'mid'=>$member['mid'],
				'level'=>$commission_level,
				'jifen'=>$money_fee_per1,
				'type'=>1,
			);
			$this->add_commission($new_commission,2);
			model('core/member')->member_credit($member['mid'],'credit6',$money_fee_per1,true,'jy_guashop','直推能量值收益');
			$this->model('member')->update_agent_level($member['mid']);
		}
		//间推能量值收益
		if($money_fee_per2>0 && $commission_level==2){
			$this->commission_order['jinfen6']+=$money_fee_per2;
			$new_commission=array(
				'mid'=>$member['mid'],
				'level'=>$commission_level,
				'jifen'=>$money_fee_per2,
				'type'=>2,
			);
			$this->add_commission($new_commission,2);
			model('core/member')->member_credit($member['mid'],'credit6',$money_fee_per2,true,'jy_guashop','间推能量值收益');
		}
		return true;
	}
	public function add_commission($data=array(),$status=1){
		$new_commission=array(
						'uniacid'=>$_SESSION['uniacid'],
						'mid'=>$data['mid'],
						'level'=>$data['level'],
						'ordersn'=>$this->order['ordersn'],
						'money'=>$data['money'],
						'jifen'=>$data['jifen'],
						'remark'=>'',
						'createtime'=>TIMESTAMP,
						'status'=>$status,
						'type'=>$data['type'],
		);
		$this->insert('commission',$new_commission);
		return true;
	}
	//盲盒投入积分
	public function manghefee($log=array()){
		$member=$this->get('member',array('mid'=>$log['mid']),array('mid','is_agent','fromuser','level_id'));
		$this->lastlevel=$member['level_id'];
		$fromuser=$member['fromuser'];
		if(!$fromuser){
			return false;
		}
		//当分销层级大于0时，逐次寻找上级推荐人并计算佣金
		$levelnum=12;
		$this->isjc_jifen=0;
		$this->last_jifen=0;
		$this->isgetping_per=0;
		for($i=0;$i<$levelnum;$i++){
			if(!$fromuser){
				break;
			}
			$member=$this->get('member',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']));
			$fromuser=$member['fromuser'];
			$this->onemanghefee($member,$i+1,$log);
			//如果他的上级是我
			$this->lastlevel=$member['level_id'];
			$ta_fromuser=$this->getcolumn('member',array('mid'=>$member['fromuser']),'fromuser');
			if(($fromuser>0 && $ta_fromuser==$fromuser) || $fromuser==$member['mid']){
				break;
			}
		}
		return true;
	}
	public function onemanghefee($member=array(),$i=1,$log=array()){		
		$level=pdo_get('jy_guashop_teamlevel',array('uniacid'=>$_SESSION['uniacid'],'id'=>$member['level_id']));
		$jifen_per1=$level['jifen_per1'];
		$jifen_per2=$level['jifen_per2'];
		$ping_per=$level['ping_per'];
        $money_ping_per=0;
        $money_jifen_per1=0;
        $money_jifen_per2=0;
		if(substr($jifen_per1,-1)=='%'){
			$money_jifen_per1 +=($log['fee']*substr($jifen_per1,0,-1))/100;
		}else{
			$money_jifen_per1 +=$jifen_per1;
		}
		if(substr($jifen_per2,-1)=='%'){
			$money_jifen_per2 +=($log['fee']*substr($jifen_per2,0,-1))/100;
		}else{
			$money_jifen_per2 +=$jifen_per2;
		}
		if($money_jifen_per1>0 && $i==1){
			$new_commission=array(
				'mid'=>$member['mid'],
				'jifen'=>$money_jifen_per1,
				'type'=>3,
			);
			$this->add_commission($new_commission,2);
			model('core/member')->member_credit($member['mid'],'credit1',$money_jifen_per1,true,'jy_guashop','团队积分收益');
		}
		$money_jifen_per2=$money_jifen_per2-$this->isjc_jifen;
		if($money_jifen_per2>0 && $i>1){
			$this->isjc_jifen +=$money_jifen_per2;
			$new_commission=array(
				'mid'=>$member['mid'],
				'jifen'=>$money_jifen_per2,
				'type'=>4,
			);
			$this->add_commission($new_commission,2);
			model('core/member')->member_credit($member['mid'],'credit1',$money_jifen_per2,true,'jy_guashop','级差积分收益');
		}
		//平一级积分收益
		if($this->last_jifen>0 && $this->lastlevel==$member['level_id'] && !$this->isgetping_per){
			if(substr($ping_per,-1)=='%'){
				$money_ping_per +=($this->last_jifen*substr($ping_per,0,-1))/100;
			}else{
				$money_ping_per +=$ping_per;
			}
			if($money_ping_per>0 && $i>1){
				$new_commission=array(
					'mid'=>$member['mid'],
					'jifen'=>$money_ping_per,
					'type'=>5,
				);
				$this->add_commission($new_commission,2);
				model('core/member')->member_credit($member['mid'],'credit1',$money_ping_per,true,'jy_guashop','平一级积分收益');
				$this->isgetping_per=1;
			}
		}
		$this->last_jifen=$money_jifen_per1+$money_jifen_per2;
		return true;
	}
	//等级能量值奖励
	public function uplevel_per($member=array()){
		$level=pdo_get('jy_guashop_teamlevel',array('uniacid'=>$_SESSION['uniacid'],'id'=>$member['level_id']));
		if($level['level_per']>0){
			$new_commission=array(
				'mid'=>$member['mid'],
				'jifen'=>$level['level_per'],
				'type'=>6,
			);
			$this->add_commission($new_commission,2);
			model('core/member')->member_credit($member['mid'],'credit6',$level['level_per'],true,'jy_guashop','等级能量值奖励');
		}
		return true;
	}
	/*
		订单完成时，把分润状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order=array()){
		if($order['ordersn']){
			$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('status'=>0,'ordersn'=>$order['ordersn']));
		}
	}
	/*
		创建结算单
	*/
	public function create_balance($merchid,$post=array()){
		if(!$merchid){
			exi('请先选择要结算的商户！','error');
		}
		if($post['pay_type']=='downline'){
			if(!$post['wechat']){
				exi('请先填写微信号！','error');
			}
			if(!$post['mobile']){
				exi('请先填写联系电话！','error');
			}
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		$dhsettimg=$this->plugin_setting('dhsettimg');
		//获取可结算分润
		$params=array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'status'=>1);
		if($dhsettimg['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($dhsettimg['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的分润！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低分润检测
		if($money<1){
			exi('可结算分润太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'merchid'=>$merchid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'wechat'=>$post['wechat'],
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($dhsettimg['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$dhsettimg['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销分润打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn){
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'代理商分润发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$remark_str=<<<TPL
订单总价【{$remark['order_price']}】
分润总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}